"""
病历数据模型
"""
from sqlalchemy import Column, Integer, String, SmallInteger, DateTime, Boolean, Text, ForeignKey, ARRAY
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from sqlalchemy.dialects.postgresql import JSONB

from  core.database import Base


class MedicalRecord(Base):
    """病历表"""
    __tablename__ = "medical_records"
    
    id = Column(Integer, primary_key=True, index=True, comment="病历ID")
    patient_id = Column(Integer, ForeignKey("patients.id"), nullable=False, index=True, comment="患者ID")
    patient_name = Column(String(100), nullable=True, comment="患者姓名")
    
    # 诊断信息
    initial_diagnosis = Column(ARRAY(String), nullable=False, comment="初步诊断")
    onset_date = Column(DateTime(timezone=True), nullable=True, comment="发病日期")
    course_days = Column(Integer, nullable=True, comment="病程(天)")
    
    # 评分信息
    nihss_score = Column(Integer, nullable=True, comment="NIHSS评分")
    
    # 病灶信息
    stroke_location = Column(Text, nullable=True, comment="梗塞部位")
    paralysis_location = Column(Text, nullable=True, comment="偏瘫部位")
    
    # 手术信息
    has_surgery = Column(Boolean, nullable=True, comment="是否手术")
    surgery_types = Column(ARRAY(String), nullable=True, comment="手术类型")
    
    # 动脉狭窄
    has_artery_stenosis = Column(Boolean, nullable=True, comment="有动脉狭窄")
    artery_types = Column(ARRAY(String), nullable=True, comment="动脉狭窄类型")
    neck_vessel_ultrasound = Column(Text, nullable=True, comment="颈部血管超声")
    
    # 语言功能
    has_language_disorder = Column(Boolean, nullable=True, comment="有语言功能障碍")
    disorder_type = Column(Text, nullable=True, comment="障碍类型")
    
    # 治疗情况：JSON 数组，元素为 {"title": str, "time": str}
    treatment_history = Column(JSONB, nullable=True, default=list, comment="治疗情况历史（JSON数组）")
    
    

    status = Column(SmallInteger, nullable=False, default=1, comment="状态 1-正常 0-禁用")
    created_at = Column(
        DateTime(timezone=True),
        nullable=False,
        server_default=func.now(),
        comment="创建时间"
    )
    updated_at = Column(
        DateTime(timezone=True),
        nullable=False,
        server_default=func.now(),
        onupdate=func.now(),
        comment="更新时间"
    )
    
    # 关系
    patient = relationship("Patient", back_populates="medical_records")
    
    def __repr__(self):
        return f"<MedicalRecord(id={self.id}, patient_id={self.patient_id}, patient_name={self.patient_name})>"

